package com.ebelter.ty.ui.activity;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.ty.R;
import com.ebelter.ty.adapters.BluetoothSerarchAdapter;
import com.ebelter.ty.adapters.bean.BluetoothDeviceInfo;
import com.ebelter.ty.model.TyManager;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 设备绑定Activity，包含未绑定提示，设备搜索及绑定成功页
 * 只有未绑定时，才会进入这里
 */

public class BindDeviceActivity extends MonitorBluetoothStatusBaseActivity{

    public static final String TAG = "BindDeviceActivity";

    private static final int  WHAT_SCAN_TIME_OVER = 88;


    private static final int  SCAN_TIME_DURATION= 12000;


    private TyManager mScaleBle;


    //蓝牙是否开启的标志
    private boolean isScaningFlag;//正在扫描的标志
    private boolean isScanFailureFlag = false;//扫描失败的标志 默认不扫描失败



    @BindView(R.id.bindActivity_title_tv)
    TextView bindActivity_title_tv;

    @BindView(R.id.btn_next_bind)
    TextView btn_next_bind;

    @BindView(R.id.cause2_tv)
    TextView cause2_tv;

//    @BindView(R.id.cause22_tv)
//    TextView cause22_tv;

    @BindView(R.id.pager_search_pairfailure_root_ll)
    LinearLayout pager_search_pairfailure_root_ll;

    @BindView(R.id.pager_search_pair_root_ll)
    LinearLayout pager_search_pair_root_ll;


    @BindView(R.id.pager_search_pair_lv)
    ListView pager_search_pair_lv;


    private BluetoothSerarchAdapter mAdapter;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_bind;
    }




    @Override
    protected void handleMsg(Message msg) {
        LogUtils.i(TAG, "-------handleMsg-----");
        switch (msg.what){
            case WHAT_SCAN_TIME_OVER:
                LogUtils.i(TAG, "-------handleMsg-----what = WHAT_SCAN_TIME_OVER = " + msg.what);
                scanTimeOver();
                break;

        }

    }

    public boolean isContain(BluetoothDevice device){
        if (mAdapter!=null&&mAdapter.getmDate()!=null){
            for ( BluetoothDeviceInfo bluetoothDevice:mAdapter.getmDate()){
                if (bluetoothDevice!=null){
                    if (TextUtils.equals(bluetoothDevice.getAddress(),device.getAddress())){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private void scanTimeOver() {
        LogUtils.i(TAG, "-------scanTimeOver ");
        isScaningFlag = false;

        if (mAdapter!=null){
            int size = mAdapter.getCount();
            LogUtils.i(TAG, "-------scanTimeOver()-----size = " + size);
            if (size>0){
                //说明扫描成功
                isScanFailureFlag = false;
                disPlayScaningLayout();
                setTitle("");
                setNextBtTitle(StringUtils.getResStr(R.string.next));
                updateNextBtStation();
            }else {
                stopScanBlueDevices();
                isScanFailureFlag = true;//说明扫描失败
                disPlayScanFailureLayout();
                setTitle(StringUtils.getResStr(R.string.Search_failed));
                setNextBtTitle(StringUtils.getResStr(R.string.Search_again));
                setNextBtEnable(true);
            }
        }

    }

    private void disPlayScanFailureLayout() {
        ViewUtils.hideView(pager_search_pair_root_ll);
        ViewUtils.displayView(pager_search_pairfailure_root_ll);
    }

    private void disPlayScaningLayout() {
        ViewUtils.displayView(pager_search_pair_root_ll);
        ViewUtils.hideView(pager_search_pairfailure_root_ll);
    }

    private void setNextBtEnable(boolean enable){
        if(btn_next_bind!=null){
            btn_next_bind.setEnabled(enable);
        }
    }

    private void setNextBtTitle(String title){
        if(btn_next_bind!=null){
            btn_next_bind.setText(title);
        }
    }


    private void setTitle(String title){
        if (bindActivity_title_tv!=null){
            bindActivity_title_tv.setText(title);
        }
    }





    @Override
    protected void initData() {


        mScaleBle = new TyManager(this);
        mScaleBle.startWord();


        mAdapter=new BluetoothSerarchAdapter(pager_search_pair_lv.getContext(),null);
        pager_search_pair_lv.setAdapter(mAdapter);



        pager_search_pair_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bluetoothDeviceInfo = mAdapter.getmDate().get(position);
                mAdapter.setBond(bluetoothDeviceInfo);
                updateNextBtStation();
            }
        });




        adapterCause2Tv();

        startScanBlueDevices();

    }


    //适配二文本
    private void adapterCause2Tv(){

        String cause22= StringUtils.getResStr(R.string.pair_failure_causes2);

        cause2_tv.setText(cause22);






    }

    @OnClick({R.id.iv_back_bind,R.id.btn_next_bind})
    public void btClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_bind:
                finish();
                break;
            case R.id.btn_next_bind:
                if (bluetoothDeviceInfo!=null&&TextUtils.equals(btn_next_bind.getText().toString().trim(), StringUtils.getResStr(R.string.next))){

                    LogUtils.i(TAG,"------------准备跳到绑定成功界面---"+bluetoothDeviceInfo);
//                    Intent intent=new Intent(this,BindDeviceSuccessActivity.class);
//                    intent.putExtra(BindDeviceSuccessActivity.NAME,bluetoothDeviceInfo.getName());
//                    intent.putExtra(BindDeviceSuccessActivity.ADDRESS,bluetoothDeviceInfo.getAddress());
//                    startActivity(intent);

                }else if (TextUtils.equals(btn_next_bind.getText().toString().trim(), StringUtils.getResStr(R.string.Search_again))){
                    searvhAgaint();
                }
                break;

        }
    }

    private BluetoothDeviceInfo bluetoothDeviceInfo;

    private void updateNextBtStation(){
        btn_next_bind.setEnabled(bluetoothDeviceInfo!=null);
    }

//    private ScanResultCallback scanResultCallback=new ScanResultCallback() {
//        @Override
//        public void onDiscovered(BluetoothDevice device) {
//            discorverOneDevice(device);
//        }
//    };

    @Override
    protected void onStart() {
        super.onStart();
       // startScanBlueDevices();
    }

    private void startScanBlueDevices(){
        if (mScaleBle==null)return;
        isScaningFlag = true;
        isScanFailureFlag = false;
        mScaleBle.stopScan();
//        if (!mScaleBle.isScaning()) {
//            LogUtils.i(TAG, "-------蓝牙开始扫描-----");
//            disPlayScaningLayout();
//            mScaleBle.startScan(scanResultCallback);
//          //  removeMessages(WHAT_SCAN_TIME_OVER);//多少秒后检查是否扫描成功的handle指令
//            boolean isSendOut = sendEmptyMessageDelayed(WHAT_SCAN_TIME_OVER,SCAN_TIME_DURATION);
//            LogUtils.i(TAG, "-------蓝牙开始扫描-----isSendOut = "+isSendOut);
//
//        } else {
//            LogUtils.i(TAG, "-------蓝牙正在扫描-----");
//        }
    }

    private void stopScanBlueDevices(){
        if (mScaleBle==null)return;
//        if (mScaleBle.isScaning()) {
//            LogUtils.i(TAG, "-------蓝牙停止扫描-----");
//            mScaleBle.stopScan();
//        }
    }







    private void discorverOneDevice(final BluetoothDevice device){
        if (device == null || TextUtils.isEmpty(device.getAddress())) {
           // ULog.i(TAG, TAG + "---扫描到的蓝牙设备不正确");
            return;
        }
       // ULog.i(TAG, Thread.currentThread().getName() + "-onDiscovered---Name = " + device.getName() + "---Address = " + device.getAddress());

            boolean isContain = isContain(device);//主要是判断扫描到的蓝牙设备是否列表了
            if (!isContain) {
            //    ULog.i(TAG, device.getAddress() + "列表中不包含此设备，准备添加至列表");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        addBlueToothDevice(new BluetoothDeviceInfo(device.getAddress(), device.getName()));
                    }
                });
            }

    }

    private void addBlueToothDevice(BluetoothDeviceInfo bluetoothDeviceInfo){
        if (mAdapter!=null){
            mAdapter.addDate(bluetoothDeviceInfo);
        }
    }

    private void searvhAgaint() {
      //  ULog.i(TAG, "-----------searvhAgaint-----");
        setTitle("");
        btn_next_bind.setText(StringUtils.getResStr(R.string.next));
        btn_next_bind.setEnabled(false);
        startScanBlueDevices();
    }





    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mScaleBle != null) {
            mScaleBle.stopScan();
        }
    }


}
